package com.ktgj.other.service.impl;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.ktgj.common.core.annotation.Excel;
import com.ktgj.common.core.domain.R;
import com.ktgj.common.core.enums.EmHelper;
import com.ktgj.common.core.web.domain.AjaxResult;
import com.ktgj.customer.api.RemoteCustomerService;
import com.ktgj.customer.api.domain.CouponDto;
import com.ktgj.customer.api.domain.Customer;
import com.ktgj.other.common.TongChengUtils;
import com.ktgj.other.domain.*;
import com.ktgj.other.domain.common.*;
import com.ktgj.other.domain.vo.*;
import com.ktgj.other.mapper.*;
import com.ktgj.other.utils.GaoDeUtil;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ktgj.other.service.IEtSceneryService;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;

/**
 * 景点Service业务层处理
 * 
 * @author ruoyi
 * @date 2022-07-22
 */
@Service
public class EtSceneryServiceImpl implements IEtSceneryService 
{
    @Autowired
    private EtSceneryMapper etSceneryMapper;
    @Autowired
    private EtDimAreaMapper etDimAreaMapper;
    @Autowired
    private EtSceneryimageMapper etSceneryimageMapper;
    @Autowired
    private EtScenerythemeMapper etScenerythemeMapper;
    @Autowired
    private EtPartnerthemeMapper etPartnerthemeMapper;
    @Autowired
    private EtSceneryticketMapper etSceneryticketMapper;
    @Autowired
    private EtPartnerconsumerMapper etPartnerconsumerMapper;
    @Autowired
    private EtSceneryticketCheckwayMapper etSceneryticketCheckwayMapper;
    @Autowired
    private EtPartnercheckwayMapper etPartnercheckwayMapper;
    @Autowired
    private EtSceneryticketCalendarMapper etSceneryticketCalendarMapper;
    @Autowired
    private RemoteCustomerService remoteCustomerService;
    @Autowired
    private EtPartnerareaMapper etPartnerareaMapper;

    /**
     * 查询景点
     * 
     * @param etsceneryid 景点ID
     * @return 景点
     */
    @Override
    public EtScenery selectEtSceneryById(Long etsceneryid)
    {
        return etSceneryMapper.selectEtSceneryById(etsceneryid);
    }

    /**
     * 查询景点列表
     * 
     * @param etScenery 景点
     * @return 景点
     */
    @Override
    public List<EtScenery> selectEtSceneryList(EtScenery etScenery)
    {
        return etSceneryMapper.selectEtSceneryList(etScenery);
    }

    /**
     * 新增景点
     * 
     * @param etScenery 景点
     * @return 结果
     */
    @Override
    public int insertEtScenery(EtScenery etScenery)
    {
        return etSceneryMapper.insertEtScenery(etScenery);
    }

    /**
     * 修改景点
     * 
     * @param etScenery 景点
     * @return 结果
     */
    @Override
    public int updateEtScenery(EtScenery etScenery)
    {
        return etSceneryMapper.updateEtScenery(etScenery);
    }

    /**
     * 批量删除景点
     * 
     * @param etsceneryids 需要删除的景点ID
     * @return 结果
     */
    @Override
    public int deleteEtSceneryByIds(Long[] etsceneryids)
    {
        return etSceneryMapper.deleteEtSceneryByIds(etsceneryids);
    }

    /**
     * 删除景点信息
     * 
     * @param etsceneryid 景点ID
     * @return 结果
     */
    @Override
    public int deleteEtSceneryById(Long etsceneryid)
    {
        return etSceneryMapper.deleteEtSceneryById(etsceneryid);
    }

    /**
     * 景点列表
     * */
    @Override
    public List<EtScenery> sceneryList(SceneryListVo sceneryListVo) throws Exception {
        GaoDeUtil gaoDeUtil = new GaoDeUtil();

        if (sceneryListVo.getCityName() == null || sceneryListVo.getCityName().equals("")){
            if (sceneryListVo.getLng() != null && sceneryListVo.getLat() != null &&
                    !sceneryListVo.getLng().equals("") && !sceneryListVo.getLat().equals("")){
                String cityName = gaoDeUtil.cityName(sceneryListVo.getLng(), sceneryListVo.getLat());
                sceneryListVo.setCityName(cityName);
            }
            else {
                throw new Exception("缺少必要参数");
            }
        }

        EtDimArea etDimArea = null;
        List<EtPartnerarea> etPartnerareas = etPartnerareaMapper.dimArea(sceneryListVo.getCityName());
//        if (etPartnerareas != null && etPartnerareas.size() > 0){
//            for (EtPartnerarea etPartnerarea : etPartnerareas) {
//                EtDimArea dimArea = etDimAreaMapper.selectEtDimAreaById(etPartnerarea.getAreaid());
//                if (dimArea.getParentareaid() != null && dimArea.getParentareaid() != 0){
//                    etDimArea = dimArea;
//                    break;
//                }
//            }
//        }


//        if (etDimArea != null){
//            sceneryListVo.setCityId(etDimArea.getAreaid());
//        }
//        else {
//            throw new Exception("没有" + sceneryListVo.getCityName() + "的记录");
//        }
        if (etPartnerareas.size()>0)
        {
            sceneryListVo.setCityId(etPartnerareas.get(0).getAreaid());
        }

        List<Long> idList = new ArrayList<>();
        List<EtScenery> etSceneryList = etSceneryMapper.sceneryList(sceneryListVo);
        if (etSceneryList != null && etSceneryList.size() > 0){
            for (EtScenery etScenery : etSceneryList) {

                List<String> math = math(etScenery.getDatacontents(), "img", "src");
                if (math != null && math.size() > 0){
                    etScenery.setUrl(math.get(0));
                }
                List<String> labelList = new ArrayList<>();
                List<EtScenerytheme> scenerytheme = etScenerythemeMapper.scenerytheme(etScenery.getEtsceneryid());
                if (scenerytheme != null && scenerytheme.size() > 0){
                    for (EtScenerytheme etScenerytheme : scenerytheme) {
                        EtPartnertheme etPartnertheme = etPartnerthemeMapper.selectEtPartnerthemeById(etScenerytheme.getPartnerthemeid());
                        if (etPartnertheme != null){
                            labelList.add(etPartnertheme.getPartnerthemename());
                        }
                    }
                }
                etScenery.setLabelList(labelList);
                etScenery.setCity(etDimArea.getName());

                EtDimArea dimArea = etDimAreaMapper.selectEtDimAreaById(etDimArea.getParentareaid());
                etScenery.setProvince(dimArea.getName());

                Double aDouble = gaoDeUtil.distanceMeter(sceneryListVo.getLng(), sceneryListVo.getLat(), etScenery.getLongitude(), etScenery.getLatitude());
                aDouble = aDouble / 1000;
                String distance = String.format("%.2f", aDouble);

                etScenery.setDistance(distance);

                List<Double> amount = new ArrayList<>();
                List<EtSceneryticket> etSceneryticketList = etSceneryticketMapper.amount(etScenery.getEtsceneryid());
                if (etSceneryticketList != null &&etSceneryticketList.size() > 0){
                    for (EtSceneryticket etSceneryticket : etSceneryticketList) {
                        amount.add(etSceneryticket.getMarketprice().doubleValue());
                        amount.add(etSceneryticket.getTcamountprice().doubleValue());
                        amount.add(etSceneryticket.getAgentprice().doubleValue());
                    }
                    etScenery.setReserve("true");
                }
                else {
                    etScenery.setReserve("false");
                    idList.add(etScenery.getEtsceneryid());
                }

                if (amount != null && amount.size() > 0){
                    amount.sort((x, y) -> Double.compare(x, y));
                    etScenery.setAmount(amount.get(0).toString());
                }
            }

            if (sceneryListVo.getReserve().equals("true") && idList != null && idList.size() > 0){
                for (Long aLong : idList) {
                    for (int i = 0; i < etSceneryList.size(); i++) {
                        if (aLong == etSceneryList.get(i).getEtsceneryid()){
                            etSceneryList.remove(i);
                            i--;
                        }
                    }
                }
            }

            if (sceneryListVo.getThemeIdList() != null && sceneryListVo.getThemeIdList().size() > 0){
                List<EtScenerytheme> etScenerythemes = etScenerythemeMapper.themeIdList(sceneryListVo.getThemeIdList());
                for (EtScenerytheme etScenerytheme : etScenerythemes) {
                    for (int i = 0; i < etSceneryList.size(); i++) {
                        if (etScenerytheme.getEtsceneryid() == etSceneryList.get(i).getEtsceneryid()){
                            etSceneryList.remove(i);
                            i--;
                        }
                    }
                }
            }

            if (sceneryListVo.getDistance() != null && !sceneryListVo.getDistance().equals("")){
                for (int i = 0; i < etSceneryList.size(); i++) {
                    if (new BigDecimal(etSceneryList.get(i).getDistance()).compareTo(new BigDecimal(sceneryListVo.getDistance())) != 1){
                        etSceneryList.remove(i);
                        i--;
                    }
                }
            }

            if (sceneryListVo.getSort() != null){
                if (sceneryListVo.getSort().equals(EmHelper.OrderStatus.sales.getValue())){
                    etSceneryList.sort((x, y) -> Double.compare(y.getSalesvolume(), x.getSalesvolume()));
                }
                else if (sceneryListVo.getSort().equals(EmHelper.OrderStatus.level.getValue())){
                    etSceneryList.sort((x, y) -> Double.compare(y.getGrade(), x.getGrade()));
                }
            }

        }

        return etSceneryList;
    }

    /**
     * 人气景点
     * */
    @Override
    public List<EtScenery> popular() {
        List<String> nameList = new ArrayList<>();
        nameList.add("故宫博物馆");
        nameList.add("八达岭长城");
        nameList.add("天坛公园");
        nameList.add("北京环球度假村");
        nameList.add("古北水镇");
        List<EtScenery> popular = etSceneryMapper.popular(nameList);

        if (popular != null && popular.size() > 0){
            for (EtScenery scenery : popular) {
                EtSceneryimage etSceneryimage = etSceneryimageMapper.sceneryimageUrl(scenery.getEtsceneryid());
                if (etSceneryimage != null){
                    scenery.setUrl(etSceneryimage.getImagepath());
                }

                List<Double> amount = new ArrayList<>();
                List<EtSceneryticket> etSceneryticketList = etSceneryticketMapper.amount(scenery.getEtsceneryid());
                if (etSceneryticketList != null &&etSceneryticketList.size() > 0){
                    for (EtSceneryticket etSceneryticket : etSceneryticketList) {
                        amount.add(etSceneryticket.getMarketprice().doubleValue());
                        amount.add(etSceneryticket.getTcamountprice().doubleValue());
                        amount.add(etSceneryticket.getAgentprice().doubleValue());
                    }
                }

                if (amount != null && amount.size() > 0){
                    amount.sort((x, y) -> Double.compare(x, y));
                    scenery.setAmount(amount.get(0).toString());
                }
            }
        }
        return popular;
    }

    /**
     * 景点详情
     * */
    @Override
    public AttractionDetailsVo attractionDetails(Long id) {
        AttractionDetailsVo attractionDetailsVo = new AttractionDetailsVo();
        EtScenery etScenery = etSceneryMapper.attractionDetails(id);
        if (etScenery != null){
            attractionDetailsVo.setId(etScenery.getSceneryid());
            attractionDetailsVo.setName(etScenery.getName());
            attractionDetailsVo.setLevel(etScenery.getGrade());

            List<String> label = new ArrayList<>();
            List<EtScenerytheme> scenerytheme = etScenerythemeMapper.scenerytheme(etScenery.getEtsceneryid());
            if (scenerytheme != null && scenerytheme.size() > 0){
                for (EtScenerytheme etScenerytheme : scenerytheme) {
                    EtPartnertheme etPartnertheme = etPartnerthemeMapper.selectEtPartnerthemeById(etScenerytheme.getPartnerthemeid());
                    if (etPartnertheme != null){
                        label.add(etPartnertheme.getPartnerthemename());
                    }
                }
            }
            attractionDetailsVo.setLabel(label);

            List<String> url = new ArrayList<>();
            List<EtSceneryimage> etSceneryimages = etSceneryimageMapper.imageUrl(etScenery.getEtsceneryid());
            if (etSceneryimages != null && etSceneryimages.size() > 0){
                for (EtSceneryimage etSceneryimage : etSceneryimages) {
                    url.add(etSceneryimage.getImagepath());
                }
            }
            attractionDetailsVo.setUrl(url);

            attractionDetailsVo.setTime(etScenery.getBusinesshours());
            attractionDetailsVo.setAddress(etScenery.getAddress());

            List<BookingVo> bookingVoList = new ArrayList<>();
            List<EtPartnerconsumer> etPartnerconsumers = etPartnerconsumerMapper.partnerconsumerList();
            if (etPartnerconsumers != null && etPartnerconsumers.size() > 0){
                for (EtPartnerconsumer etPartnerconsumer : etPartnerconsumers) {
                    BookingVo bookingVo = new BookingVo();
                    bookingVo.setId(etPartnerconsumer.getPartnerconsumerid());
                    bookingVo.setName(etPartnerconsumer.getPartnerconsumername());

                    List<Double> priceList = new ArrayList<>();
                    List<EtSceneryticket> amount = etSceneryticketMapper.amount(etScenery.getEtsceneryid());
                    if (amount != null && amount.size() > 0){
                        for (EtSceneryticket etSceneryticket : amount) {
                            priceList.add(etSceneryticket.getMarketprice().doubleValue());
                            priceList.add(etSceneryticket.getTcamountprice().doubleValue());
                            priceList.add(etSceneryticket.getAgentprice().doubleValue());
                        }
                    }
                    if (priceList != null && priceList.size() > 0){
                        priceList.sort((x, y) -> Double.compare(x, y));
                        bookingVo.setPrice(priceList.get(0).toString());
                    }

                    List<BookingDetailsVo> bookingDetailsVoList = new ArrayList<>();
                    List<EtSceneryticket> etSceneryticketList = etSceneryticketMapper.priceList(etScenery.getEtsceneryid(), etPartnerconsumer.getPartnerconsumerid());
                    if (etSceneryticketList != null &&etSceneryticketList.size() > 0){
                        for (EtSceneryticket etSceneryticket : etSceneryticketList) {
                            BookingDetailsVo bookingDetailsVo = new BookingDetailsVo();
                            bookingDetailsVo.setId(etSceneryticket.getSceneryticketid());
                            bookingDetailsVo.setName(etSceneryticket.getTicketname());
                            if (etSceneryticket.getMarketprice() != null){
                                bookingDetailsVo.setPrice(etSceneryticket.getMarketprice().toString());
                            }

                            bookingDetailsVo.setTime(etSceneryticket.getReservebeforetime());
                            bookingDetailsVoList.add(bookingDetailsVo);
                        }
                    }
                    bookingVo.setBookingDetailsVoList(bookingDetailsVoList);
                    bookingVoList.add(bookingVo);
                }
            }
            attractionDetailsVo.setBookingVoList(bookingVoList);
        }
        return attractionDetailsVo;
    }

    /**
     * 门票详情介绍
     * */
    @Override
    public IntroduceVo introduce(Long id) {
        IntroduceVo introduceVo = new IntroduceVo();
        EtSceneryticket etSceneryticket = etSceneryticketMapper.selectEtSceneryticketById(id);
        if (etSceneryticket != null){
            EtScenery etScenery = etSceneryMapper.selectEtSceneryById(etSceneryticket.getEtsceneryid());
            if (etScenery != null){
                introduceVo.setIntroduce(etScenery.getDetailintroduce());
                introduceVo.setTime(etScenery.getBusinesshours());
                introduceVo.setPolicy(etScenery.getFavouredpolicy());

                List<String> certificate = new ArrayList<>();
                List<EtSceneryticketCheckway> etSceneryticketCheckways = etSceneryticketCheckwayMapper.sceneryticketCheckwayList(id);
                if (etSceneryticketCheckways != null && etSceneryticketCheckways.size() > 0){
                    for (EtSceneryticketCheckway etSceneryticketCheckway : etSceneryticketCheckways) {
                        EtPartnercheckway etPartnercheckway = etPartnercheckwayMapper.selectEtPartnercheckwayById(etSceneryticketCheckway.getPartnercheckwayid());
                        if (etPartnercheckway != null){
                            certificate.add(etPartnercheckway.getPartnercheckwayname());
                        }
                    }
                }
                introduceVo.setCertificate(certificate);
            }
        }
        return introduceVo;
    }

    /**
     * 填写订单
     * */
    @Override
    public WriteOrder writeOrder(WriteOrderVo writeOrderVo, HttpServletRequest request) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        Date date = new Date();
        String time  = format.format(date);

        String token = request.getHeader("token");
        Customer customer = remoteCustomerService.getLoginCustomerByToken(token).getData();
        if (customer != null){
            writeOrderVo.setCustomerId(customer.getCustomerId());
        }
        else {
            throw new Exception("登录已过期");
        }

        WriteOrder writeOrder = new WriteOrder();
        EtSceneryticket etSceneryticket = etSceneryticketMapper.selectEtSceneryticketById(writeOrderVo.getId());
        if (etSceneryticket != null){
            writeOrder.setTicketName(etSceneryticket.getProductunitname());
        }

        EtSceneryticketCalendar etSceneryticketCalendar = etSceneryticketCalendarMapper.sceneryticketCalendar(writeOrderVo.getId(), Long.valueOf(time));
        if (etSceneryticketCalendar != null){
            writeOrder.setPrice(etSceneryticketCalendar.getAgentamount().toString());
            R<CouponDto> couponDtoR = remoteCustomerService.queyUserCouponById(writeOrderVo.getCustomerId(), etSceneryticketCalendar.getAgentamount());
            if (couponDtoR.getData() != null){
                writeOrder.setCouponDto(couponDtoR.getData());
            }
        }

        R<Long> longR = remoteCustomerService.queyUserCreditsNumByCustomerId(writeOrderVo.getCustomerId());
        if (longR.getData() != null){
            writeOrder.setIntegral(longR.getData().toString());
        }

        R<Long> goldByCustomerId = remoteCustomerService.selectAvailableGoldByCustomerId(writeOrderVo.getCustomerId());
        if (goldByCustomerId.getData() != null){
            writeOrder.setGold(goldByCustomerId.getData().toString());
        }
        return writeOrder;
    }

    /**
     * 更新景点信息
     * */
    @Override
    public int save(int id) {
        TongChengUtils tongChengUtils = new TongChengUtils();
        TongChengInfoDetail tongChengInfoDetail = new TongChengInfoDetail();
        RequestBodyDetail requestBodyDetail = new RequestBodyDetail();
        requestBodyDetail.setSceneryId(id);
        HttpTongChengInfoDetail sceneryDetailService = tongChengUtils.getSceneryDetailService(tongChengInfoDetail);

        EtScenery details = etSceneryMapper.attractionDetails(Long.valueOf(id));

        EtScenery etScenery = new EtScenery();
        etScenery.setSceneryid(Long.valueOf(id));
        etScenery.setName(sceneryDetailService.getSceneryName());
        etScenery.setGrade(Long.valueOf(sceneryDetailService.getSceneryGrade()));
        etScenery.setAddress(sceneryDetailService.getSceneryAddress());

        List<EtDimArea> etDimAreaList = etDimAreaMapper.cityId(sceneryDetailService.getSceneryProvinceName());
        if (etDimAreaList != null && etDimAreaList.size() > 0){
            for (EtDimArea etDimArea : etDimAreaList) {
                if (etDimArea.getParentareaid() == null || etDimArea.getParentareaid() == 0){
                    etScenery.setProvinceareaid(etDimArea.getAreaid());
                }
            }
        }

        List<EtDimArea> etDimAreas = etDimAreaMapper.cityId(sceneryDetailService.getSceneryProvinceName());
        if (etDimAreas != null && etDimAreas.size() > 0){
            for (EtDimArea etDimArea : etDimAreas) {
                if (etDimArea.getParentareaid() != null && etDimArea.getParentareaid() != 0){
                    etScenery.setCityareaid(etDimArea.getAreaid());
                }
            }
        }

        if (sceneryDetailService.getUserNotes() != null){
            if (sceneryDetailService.getUserNotes().getBusinessHours() != null){
                int i = sceneryDetailService.getUserNotes().getBusinessHours().indexOf(":");
                if (i != -1){
                    String substring = sceneryDetailService.getUserNotes().getBusinessHours().substring(i + 1);
                    etScenery.setBusinesshours(substring);
                }
            }

            etScenery.setFavouredpolicy(sceneryDetailService.getUserNotes().getFavouredPolicy());
        }

        etScenery.setLongitude(sceneryDetailService.getSceneryLongitude());
        etScenery.setLatitude(sceneryDetailService.getSceneryLatitude());
        etScenery.setLocationpoint(sceneryDetailService.getSceneryLongitude() + "," + sceneryDetailService.getSceneryLatitude());
        etScenery.setTrafficguide(sceneryDetailService.getSceneryTrafficGuide());
        etScenery.setPartnerid(1l);
        etScenery.setUpdateTime(new Date());

        int i;
        if (details != null){
            i = etSceneryMapper.updateIncrementType(etScenery);
        }
        else {
            i = etSceneryMapper.insertEtScenery(etScenery);
        }

        EtScenery scenery = etSceneryMapper.attractionDetails(Long.valueOf(id));

        if (sceneryDetailService.getPictureListInfo() != null && sceneryDetailService.getPictureListInfo().size() > 0){
            etSceneryimageMapper.delUrl(scenery.getEtsceneryid());

            for (PictureListInfo pictureListInfo : sceneryDetailService.getPictureListInfo()) {
                EtSceneryimage etSceneryimage = new EtSceneryimage();

                Long sceneryImageId = System.currentTimeMillis() / 1000;
                etSceneryimage.setSceneryimageid(sceneryImageId);
                etSceneryimage.setImagepath(pictureListInfo.getSceneryImgPath());
                etSceneryimage.setEtsceneryid(scenery.getEtsceneryid());
                etSceneryimageMapper.insertEtSceneryimage(etSceneryimage);
            }
        }
        return i;
    }

    /**
     * 获取指定HTML标签的指定属性的值
     * */
    public List<String> math(String source, String element, String attr){
        List<String> result = new ArrayList<String>();
        String reg = "<" + element + "[^<>]*?\\s" + attr + "=['\"]?(.*?)['\"]?(\\s.*?)?>";
        Matcher m = Pattern.compile(reg).matcher(source);
        while (m.find()){
            String r = m.group(1);
            result.add(r);
        }
        return result;
    }
}
